package com.module.codeBind.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import base.common.CUDEnum;
import base.dao.GenericHibernateDao;
import base.util.Tools;

import com.module.antiFake.vo.AppAttr;
import com.module.antiFake.vo.AppAttrValuePo;
import com.module.codeBind.util.CodeBindBeanUtil;
import com.module.codeBind.vo.AppAttrValue;
import com.module.codeBind.vo.CodeBind;



public class AppAttrValueDao extends GenericHibernateDao<AppAttrValue, String> {
	static AppAttrValueDao dao;

	AppAttrValueDao() {

	}

	public static AppAttrValueDao getInstance() {
		if (dao == null) {
			dao = new AppAttrValueDao();
		}
		return dao;
	}

	/**
	 * 根据绑定删除属性值
	 * 
	 * @param session
	 *            事物会话
	 * @param item
	 *            码绑定对象
	 * @return 成功或者失败
	 */
	public void delete(Session session, CodeBind item) {
		String hql = "update AppAttrValue set updaterId = ?,updateTime=?,status =? where bindId in ("
				+ item.getId() + ")";
		Query query = session.createQuery(hql);
		query.setParameter(0, item.getUpdaterId());
		query.setParameter(1, new Date());
		query.setParameter(2, CUDEnum.D.toString());
		query.executeUpdate();

	}

	public void save(Session session,List<AppAttrValue> list, String bindId, String userId) {
		for (AppAttrValue v : list) {
			v.setBindId(bindId);
			if (Tools.isValid(v.getId())) {
				v.setUpdaterId(userId);
				v.setUpdateTime(new Date());
				v.setStatus(CUDEnum.U.toString());
			} else {
				v.setCreaterId(userId);
				v.setCreateTime(new Date());
				v.setStatus(CUDEnum.C.toString());
			}
			session.merge(v);
		}
	}
	@SuppressWarnings("unchecked")
	public List<AppAttrValue> getAttrAndValueByApp(Session session,Connection conn,String codeAppId,
			String bindId) throws SQLException {
		List<AppAttrValue> res = new ArrayList<AppAttrValue>();// 将用于存放保存的结果集合
		if (Tools.isValid(bindId)) {
			StringBuffer sql = new StringBuffer("select aav.c_appAttrValue_id");
			sql.append(",aav.c_appAttr_id");
			sql.append(",aav.c_appAttr_value");
			sql.append(",aav.c_bind_id");
			sql.append(",aav.c_createrid");
			sql.append(",aav.d_createtime");
			sql.append(",aav.c_updaterid");
			sql.append(",aav.c_status");
			sql.append(",aav.d_updatetime");
			sql.append(",aav.c_app_attr_value_size");
			sql.append(",obj.c_field_type,obj.c_appAttr_name");
			sql.append(",obj.c_appAttr_id as attrId");
			sql.append(" from endw_appattr as obj left join endw_appattrvalue as aav ");
			sql.append(" on obj.c_appAttr_id=aav.c_appAttr_id and aav.c_bind_id='"
					+ bindId + "'");
			sql.append(" where  obj.c_status !='D' and obj.c_codeApp_id = '"
					+ codeAppId + "'");
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sql.toString());
			try {
				while (rs.next()) {
					AppAttrValue value = new AppAttrValue();
					value.setId((String) rs.getString("c_appAttrValue_id"));
					value.setAppAttrId((String) rs.getString("c_appAttr_id"));
					value.setValue((String) rs.getString("c_appAttr_value"));
					value.setBindId((String) rs.getString("c_bind_id"));
					value.setCreaterId((String) rs.getString("c_createrid"));
					value.setCreateTime((Date) rs.getDate("d_createtime"));
					value.setStatus((String) rs.getString("c_status"));
					value.setUpdateTime((Date) rs.getDate("d_updatetime"));
					value.setUpdaterId((String) rs.getString("c_updaterid"));
					value.setAppAttrValueSize((Integer) rs
							.getInt("c_app_attr_value_size"));
					value.setFieldType((String) rs.getString("c_field_type"));
					value.setAppAttrName((String) rs
							.getString("c_appAttr_name"));
					value.setAppAttrId((String) rs.getString("attrId"));
					if (Tools.isBlank(value.getId())) {
						value.setAppAttrId((String) rs.getString("attrId"));
					}
					if (value.getFieldType().equals("comboBox")) {
						value.setAppAttrComboList(session.createQuery(
								"from AppAttrCombo as ac where ac.appAttrId='"
										+ value.getAppAttrId() + "'").list());
					}
					res.add(value);
				}
			} finally {
				close(stmt);
				close(rs);
			}
		} else {
			StringBuffer hql = new StringBuffer(
					"from AppAttr as obj where obj.status !='D' and obj.codeAppId = ?");
			
			List<AppAttr> valueres = session.createQuery(hql.toString())
					.setString(0, codeAppId).list();
			for (AppAttr attr : valueres) {
				AppAttrValue value = new AppAttrValue();
				value.setFieldType(attr.getFieldType());
				value.setAppAttrName(attr.getName());
				value.setAppAttrId(attr.getId());
				if (value.getFieldType().equals("comboBox")) {
					value.setAppAttrComboList(session.createQuery(
							"from AppAttrCombo as ac where ac.appAttrId='"
									+ value.getAppAttrId() + "'").list());
				}
				res.add(value);
			}
		}
		return res;
	}

	public List<AppAttrValuePo> findAppByCodeFlashBuy(Session session,CodeBindBeanUtil beanUtil) {
		List<AppAttrValuePo> list = new ArrayList<AppAttrValuePo>();
		StringBuffer sb = new StringBuffer();
		sb.append("select obj.value,obj.appAttrValueSize,aa.fieldType from AppAttrValue as obj, AppAttr as aa, CodeApp as ca where obj.appAttrId=aa.id and aa.codeAppId=ca.id and obj.status !='D'");
		sb.append(" and obj.bindId in (select c.bindId  from Code as c where c.code = '");
		sb.append(beanUtil.getCodebind().getCode());
		sb.append("') and ca.appCode ='")
				.append(beanUtil.getCodeapp().getAppCode()).append("'");
		List result = session.createQuery(sb.toString()).list();
		Iterator it = result.iterator();
		while (it.hasNext()) {
			AppAttrValuePo po = new AppAttrValuePo();
			Object[] tuple = (Object[]) it.next();
			po.setValue((String) tuple[0]);
			po.setAppAttrValueSize((Integer) tuple[1]);

			po.setFieldType((String) tuple[2]);
			list.add(po);
		}
		return list;
	}
}
